package com.zlzlib.libnetty.ws.handler;


import com.zlzlib.libnetty.util.Util;
import com.zlzlib.libnetty.ws.WebSocketClient;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Created by zlz on 2019/11/19.
 * WebSocket心跳任务管理器
 */
public class HeartbeatWebHandler extends ChannelInboundHandlerAdapter {

    private final WebSocketClient imsClient;

    public HeartbeatWebHandler(WebSocketClient imsClient) {
        this.imsClient = imsClient;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {// 规定时间内没向服务端发送消息，即发送一个心跳包
                if (heartbeatTask == null) {
                    heartbeatTask = new HeartbeatTask();
                }
                imsClient.getLoopGroup().execWorkTask(heartbeatTask);
            }else if(state == IdleState.READER_IDLE){
                // 规定时间内没收到服务端响应，手动回应
                Util.logInfo("心跳超时==");
                imsClient.onHeartPong();
            }
        }
    }

    private HeartbeatTask heartbeatTask;

    private class HeartbeatTask implements Runnable {

        public HeartbeatTask() {
        }

        @Override
        public void run() {
            //ping一次服务器 发送一次心跳
            Util.logInfo("发送心跳消息==");
            long ping = imsClient.ping();
            Util.logInfo("当前心跳回复为：" + ping + "ms");
            if(ping> imsClient.getHeartbeatInterval()){
                imsClient.resetConnect();
            }
        }
    }

}
